<!--
 * @Author: 冯本桥
 * @Date: 2025-02-13 13:44:40
 * @LastEditTime: 2025-03-07 15:53:36
 * @LastEditors: 冯本桥
 * @Description:预约到访
 * @FilePath: \teach_system_fe\src\views\sellCrm\subscribeVisit.vue
-->
<template>
  <div v-loading="loading">
    <div class="cad-box">
      <el-form
        ref="ruleForm"
        :inline="true"
        :model="searchValue"
        class="demo-form-inline"
      >
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="" prop="channelId">
              <el-select
                v-model="searchValue.status"
                style="width: 100%"
                clearable
                placeholder="请选到访状态"
              >
                <el-option label="已到访" value="1" />
                <el-option label="未到访" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="" prop="name">
              <el-input
                v-model="searchValue.name"
                clearable
                placeholder="请输入家长姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-date-picker
              v-model="searchValue.visitTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" @click="getTableList">确定</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="content-table cad-box">
      <div style="margin-bottom: 30px">
        <el-button type="primary" @click="download">导出</el-button>
        <el-button @click="add">新增</el-button>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%; margin: 30px 0"
        :header-cell-style="{
          backgroundColor: '#fafafc',
          color: '#000000',
        }"
      >
        <el-table-column
          v-for="(item, index) in fromConfig.subscribeVisitTableTile"
          :key="index"
          :prop="item.key"
          :label="item.name"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">
            <span
              v-if="item.data"
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <div
                v-if="
                  scope.row[item.key] !== '' && scope.row[item.key] !== null
                "
                :style="{
                  backgroundColor:
                    scope.row[item.key] * 1 === 1 ? '#7FC73C' : '#FF5757',
                }"
                class="state-box"
              />
              <span> {{ item.data[scope.row[item.key]] || "-" }}</span>
            </span>
            <span v-else>
              {{ scope.row[item.key] || "-" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="followUp(scope.row)">
              跟进
            </el-button>
            <el-button type="text" size="small" @click="info(scope.row)">
              详情
            </el-button>
            <el-button type="text" size="small" @click="edit(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right">
        <el-pagination
          :current-page="pagination.pageNum"
          :page-sizes="[10, 15, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-drawer
      :title="`${drawerTitle}到访`"
      :visible.sync="drawer"
      :before-close="beforeClose"
      :destroy-on-close="true"
      custom-class="add-drawer"
      :wrapper-closable="false"
    >
      <div style="padding: 0 20px">
        <from-page
          ref="expFromRef"
          :rules="fromConfig.rulesD"
          :label-width="null"
          :from-config="clueAddFrom"
          :value="fromDate"
          @submitForm="submitForm"
        />
      </div>
    </el-drawer>

    <addSubscribe
      :drawer-text="drawerText"
      :drawer="drawerFlag"
      :rules-date="fromConfig.addSubscribeVisitRules"
      :from-config="fromConfig.addSubscribeVisit"
      :text-message="subtext"
      :drawer-types="drawerTypes"
      :from-date="fromDate"
      :drawer-types-submit="drawerTypesSubmit"
      @closePage="closePage"
      @transfer="
        () => {
          transferValueVisible = true;
          transferValue = fromDate.rankp;
        }
      "
      @handOver="handOverFunction"
    />

    <el-dialog
      title="转为线索"
      :visible.sync="transferValueVisible"
      width="20%"
      :before-close="() => (transferValueVisible = false)"
    >
      <div style="text-align: center">
        <el-select
          v-model="transferValue"
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option
            v-for="item in transferValueOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="transferValueVisible = false">取 消</el-button>
        <el-button type="primary" @click="transferValueBtn">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="移交"
      :visible.sync="handOverVisible"
      width="20%"
      :before-close="() => (handOverVisible = false)"
    >
      <div style="text-align: center">
        <el-select
          v-model="handOverValue"
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option
            v-for="item in handOverOptions"
            :key="item.id"
            :label="item.realName"
            :value="item.id"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handOverVisible = false">取 消</el-button>
        <el-button type="primary" @click="handOverVisibleBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as fromConfig from './config'
import FromPage from '@/components/Basic/FromPage/index'
import addSubscribe from './component/addSubscribe.vue'
import { mapGetters } from 'vuex'
import {
  aboutVisitAdd,
  aboutVisitDeriveVisit,
  aboutVisitList,
  aboutVisitupdate,
  leadsHistoryFindByVisitId,
  leadsHistorySaveVisit
} from '@/api/educationalAdminstration'
import { getTransferStaffList } from '@/views/sellCrm/api'
import { downloadXls } from '@/utils'
import { aboutVisitupdateList } from './api/index'

export default {
  components: {
    FromPage,
    addSubscribe
  },
  data () {
    return {
      isAdd: false,
      transferValueVisible: false,
      transferValue: 0,
      transferValueOptions: [
        { value: 0, label: 'A重点客户' },
        { value: 1, label: '普通客户' },
        { value: 2, label: '非优先客户' }
      ],
      handOverVisible: false,
      handOverValue: '',
      handOverOptions: [],
      fromDate: {},
      loading: false,
      drawerTypes: true,
      drawerText: {},
      drawerTitle: '',
      subtext: [],
      drawerFlag: false,
      fromConfig: fromConfig,
      clueAddFrom: [],
      drawer: false,
      searchValue: {
        status: '',
        name: '',
        visitTime: []
      },
      tableData: [],
      pagination: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0
    }
  },
  computed: {
    ...mapGetters(['curArea'])
  },
  created () {
    this.getTableList()
  },
  mounted () {},
  methods: {
    add () {
      const json = [...this.fromConfig.subFrom]
      json.splice(json.length - 1, 0, {
        type: 'picker',
        label: '预约到访时间',
        value: 'visitTime',
        placeholder: '选择日期',
        valueFormat: 'yyyy-MM-dd hh:mm:ss'
      })
      this.fromDate = {}
      this.isAdd = true
      this.drawerTitle = '新增'
      this.clueAddFrom = json
      this.drawer = true
      this.$nextTick(() => {
        this.$refs.expFromRef.resetFields()
      })
    },

    download () {
      console.log('导出')
      this.$confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const othValue = { ...this.pagination, ...this.searchValue }
        if (this.searchValue.visitTime.length === 2) {
          othValue.initiateTime = this.searchValue.visitTime[0]
          othValue.endTime = this.searchValue.visitTime[1]
          delete othValue.visitTime
        }
        othValue.pageNum = 1
        othValue.pageSize = 111111
        aboutVisitDeriveVisit(othValue).then((res) => {
          downloadXls(res, '预约到访.xlsx')
        })
      })
    },
    async handOverFunction () {
      await this.getOptions()
      this.handOverValue = ''
      this.handOverVisible = true
    },
    async info (item) {
      console.log('详情', item)
      this.drawerText = {
        drawerTitle: '到访详情',
        cardTitle: '到访记录'
      }
      this.subtext = [
        ...this.fromConfig.subtext,
        {
          name: '备注',
          key: 'remark'
        }
      ]
      // 查询
      const data = await leadsHistoryFindByVisitId({
        type: 'aboutVisit',
        leadsId: item.id,
        pageNum: 1,
        pageSize: 100
      })
      this.drawerText.cardData = data.content
      this.fromDate = item
      this.drawerTypes = false
      this.drawerFlag = true
    },
    async transferValueBtn () {
      this.fromDate.changeStatusVal = '已转'
      this.fromDate.rankp = this.transferValue
      this.fromDate.type = 2
      await aboutVisitupdateList(this.fromDate)
      this.$message({
        message: '转为线索成功',
        type: 'success'
      })
      // 刷新
      this.transferValueVisible = false
      this.info(this.fromDate)
      //
      this.getTableList()
    },
    async getOptions () {
      const res = await getTransferStaffList({
        permission: 'teach::classes::sales_list'
      })
      this.handOverOptions = res
    },
    async handOverVisibleBtn () {
      console.log('移交', this.fromDate, this.handOverValue)
      const optionsItem = this.handOverOptions.filter(
        (item) => item.id === this.handOverValue
      )
      this.fromDate.staffId = this.handOverValue
      this.fromDate.staffName = optionsItem[0].realName
      const data = await aboutVisitupdate(this.fromDate)
      console.log('转为线索》》', data)
      this.$message({
        message: '移交成功',
        type: 'success'
      })
      this.handOverVisible = false
      // 刷新
      this.info(this.fromDate)
      //
      this.getTableList()
    },
    edit (item) {
      const json = [...this.fromConfig.subFrom]
      json.splice(json.length - 1, 0, {
        type: 'picker',
        label: '预约到访时间',
        value: 'visitTime',
        placeholder: '选择日期',
        valueFormat: 'yyyy-MM-dd'
      })
      this.isAdd = false
      this.fromDate = item
      this.fromDate.gender = String(item.gender)
      this.provinceCityArea = [item?.province, item?.city, item?.area]
      console.log('编辑', this.fromDate, this.clueAddFrom)
      this.clueAddFrom = json
      this.drawer = true
      this.drawerTitle = '编辑'
    },
    followUp (item) {
      console.log('跟进', item)
      this.drawerText = {
        drawerTitle: '跟进',
        cardTitle: '跟进信息'
      }
      this.fromDate = item
      this.fromDate.imgUrl = ''
      this.subtext = this.fromConfig.subtext

      this.drawerTypes = true
      this.drawerFlag = true
    },
    async drawerTypesSubmit (myData) {
      console.log('跟进', myData, this.fromDate)
      const myInport = {
        type: 'aboutVisit',
        leadsId: this.fromDate.id,
        ...myData
      }
      myInport.imgUrl = myInport.imgUrl?.join(',')
      const data = await leadsHistorySaveVisit(myInport)
      console.log('新增', data)
      this.$message({
        message: '跟进成功',
        type: 'success'
      })
      this.getTableList()
      this.drawerFlag = false
    },
    getTableList () {
      this.loading = true
      this.tableData = []
      const othValue = {
        ...this.pagination,
        ...this.searchValue,
        areaId: this.curArea.areaId || ''
      }
      if (this.searchValue.visitTime.length === 2) {
        othValue.initiateTime = this.searchValue.visitTime[0]
        othValue.endTime = this.searchValue.visitTime[1]
        delete othValue.visitTime
      }
      aboutVisitList(othValue)
        .then((res) => {
          console.log('res.data', res)
          this.tableData = res.content
          this.total = res.totalElements
          this.loading = false
        })
        .catch((e) => {
          this.loading = false
        })
    },
    async submitForm (myFromData) {
      const { province, city, area } = myFromData?.provinceCityArea || {}
      myFromData.province = province?.value || ''
      myFromData.city = city?.value || ''
      myFromData.area = area?.value || ''
      myFromData.homeAddress = `${province?.value || ''}${city?.value || ''}${
        area?.value || ''
      }${myFromData.address || ''}`
      if (this.isAdd) {
        myFromData.type = 2
        const data = aboutVisitAdd(myFromData)
        console.log('新增', data)
        this.$message({
          message: '新增成功',
          type: 'success'
        })
        this.getTableList()
        this.drawer = false
      } else {
        const data = await aboutVisitupdate(myFromData)
        console.log('编辑', data)
        this.$message({
          message: '编辑成功',
          type: 'success'
        })
        this.getTableList()
        this.drawer = false
      }
    },
    beforeClose () {
      this.$refs.expFromRef.resetFields()
      this.$refs.expFromRef.formDate = {}
      this.drawer = false
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagination.pageSize = val
      this.getTableList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pagination.pageNum = val
      this.getTableList()
    },
    closePage (flag) {
      this.drawerFlag = flag
    }
  }
}
</script>

<style scoped lang="scss">
.content-table {
  margin-top: 30px;
  .state-box {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 10px;
  }
}

.demo-form-inline {
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}
</style>
